package com.upcode.weighing.redisson;

import com.upcode.weighing.detect.service.DetectPointService;
import com.upcode.weighing.domain.DetectPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    private static final Logger logger= LoggerFactory.getLogger(RedisKeyExpirationListener.class);
    @Autowired
    private DetectPointService detectPointService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        logger.info("失效expiredKey:{}", expiredKey);
        if(expiredKey.startsWith("heartbeart_")){//心跳过期
            String idStr=expiredKey.substring(expiredKey.indexOf("_")+1);
            DetectPoint detectPoint = detectPointService.getById(idStr);
            detectPoint.setStatus(0);
            detectPoint.setLastOfflineTime(LocalDateTime.now());
            long duration = Duration.between(detectPoint.getOnlineStartTime(), LocalDateTime.now()).toMillis() / 1000;
            detectPoint.setOnlineDuration(duration);
            detectPointService.saveOrUpdate(detectPoint);//离线
        }
    }
}
